//
//  BSPullDownRefreshView.swift
//  上下拉刷新
//
//  Created by apple on 16/7/25.
//  Copyright © 2016年 shenqingwei. All rights reserved.
//

import UIKit

enum pullDownRefreshStatus{
    case normal
    case pulling
    case refreshing
}

class BSPullDownRefreshView: UIView {
    
    private let pullDownRefreshHeight: CGFloat=60
    
    ///开始下拉刷新的闭包
    var refreshingCallBack: (() -> Void)?
    
    ///父控件
    private var newSuperScrollView: UIScrollView?
    
    ///当前状态默认为 下拉刷新
    private var currentStatus: pullDownRefreshStatus = .normal{
        didSet{
            //判断当前状态
            switch currentStatus{
            case .normal:
                print("normal")
                
                label.text="下拉刷新"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowView.transform=CGAffineTransformIdentity
                })
            case .pulling:
                print("pulling")
                label.text="释放刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .refreshing:
                print("refreshing")
                self.arrowView.hidden=true
                self.loadingView.hidden=false
                label.text="正在刷新..."
                
                //风火轮动画
                let animation=CABasicAnimation(keyPath: "transform.rotation")
                animation.toValue = 2*M_PI
                animation.duration=0.75
                animation.repeatCount=MAXFLOAT
                animation.removedOnCompletion=false
                loadingView.layer.addAnimation(animation, forKey: nil)
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.newSuperScrollView?.contentInset.top=self.newSuperScrollView!.contentInset.top + self.pullDownRefreshHeight
                })
                //闭包传递开始刷新
                self.refreshingCallBack!()
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.frame=CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, -pullDownRefreshHeight)
        self.backgroundColor=UIColor.brownColor()
        
        //设置UI
        setupUI()
    }
    
    //MARK: - 开始刷新
    func beginRefresh(){
        self.currentStatus = .refreshing
    }
    
    ///结束刷新
    func endRefreshing(){
        if self.currentStatus == .refreshing {
            self.currentStatus = .normal
            
            self.loadingView.layer.removeAllAnimations()
            self.loadingView.hidden=true
            self.arrowView.hidden=false
            //将刷新控件退回去,回收
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.newSuperScrollView?.contentInset.top = self.newSuperScrollView!.contentInset.top - self.pullDownRefreshHeight
            })
        }
    }

    //设置UI
    private func setupUI(){
        //隐藏风火轮
        self.loadingView.hidden=true
        
        //添加
        self.addSubview(arrowView)
        self.addSubview(loadingView)
        self.addSubview(label)
        
        arrowView.translatesAutoresizingMaskIntoConstraints=false
        loadingView.translatesAutoresizingMaskIntoConstraints=false
        label.translatesAutoresizingMaskIntoConstraints=false
        
        //约束
        self.addConstraint(NSLayoutConstraint(item: arrowView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -25))
        self.addConstraint(NSLayoutConstraint(item: arrowView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        self.addConstraint(NSLayoutConstraint(item: loadingView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: arrowView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: loadingView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        self.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: arrowView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 20))
        self.addConstraint(NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
    }
    
    //即将移动到父控件时,即调用addsubview时触发
    override func willMoveToSuperview(newSuperview: UIView?) {
        if newSuperview is UIScrollView{
            self.newSuperScrollView=newSuperview as? UIScrollView
            
            //kvo监听
            self.newSuperScrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        }
    }
    
    //移除监听
    deinit{
       self.newSuperScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //实现kvo方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if self.newSuperScrollView!.dragging{
            
            if self.currentStatus == .pulling && self.newSuperScrollView?.contentOffset.y > -124{
                
                //下拉刷新view没有完全显示后修改状态,以阻止频繁进来切换状态
                self.currentStatus = .normal
            }else if self.currentStatus == .normal && self.newSuperScrollView?.contentOffset.y < -124{
                
                //下拉刷新view已经完全显示后修改状态,以阻止频繁进来切换状态
                self.currentStatus = .pulling
            }
            
        }else{
            //用户松手了,释放刷新===> 正在刷新
            if self.currentStatus == .pulling{
                self.currentStatus = .refreshing
            }
        }
    }
    
    //MARK: - 懒加载
    private lazy var arrowView: UIImageView=UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var loadingView: UIImageView=UIImageView(image: UIImage(named: "tableview_loading"))
    private lazy var label: UILabel={
        let label=UILabel()
        label.text="下拉刷新"
        
        return label
    }()
    
}
